package com.fengyunhe.manager.web;

import com.fengyunhe.common.RequestThread;
import com.fengyunhe.manager.AppException;
import com.fengyunhe.manager.service.AdminLogService;
import com.fengyunhe.utils.json.JsonObjectUtils;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public abstract class AdminBaseController {

    protected Log log = LogFactory.getLog(this.getClass());
    @Autowired
    protected AdminLogService adminLogService;

    /**
     * 异常页面控制
     *
     * @param runtimeException
     * @return
     */
    @ExceptionHandler(RuntimeException.class)
    public ModelAndView runtimeExceptionHandler(HttpServletRequest request,
                                                HttpServletResponse response, RuntimeException runtimeException) {

//       设置异常到当前线程，交由拦截器做日志记录
        RequestThread.setException(runtimeException);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("success", false);
        if (runtimeException instanceof UnauthorizedException || runtimeException instanceof AuthenticationException || runtimeException instanceof AuthorizationException) {
            map.put("msg", "对不起，您没有此操作的权限");
        } else if (runtimeException instanceof AppException) {
            map.put("msg", runtimeException.getMessage());
        } else {
            map.put("trace", ExceptionUtils.getFullStackTrace(runtimeException));
            map.put("msg", "发生错误");
            log.error("后台出现错误:" + ExceptionUtils.getFullStackTrace(runtimeException));
        }
        if ("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))) { // EXTJS
            try {
                response.setCharacterEncoding("utf-8");
                response.setContentType("text/html;charset=UTF-8");
                response.getWriter().println(JsonObjectUtils.beanToJson(map));
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        } else {
            return new ModelAndView("/admin/error", map);
        }
    }

}
